package io.renren.modules.admin.controller;

import java.util.*;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.admin.entity.WarmContentEntity;
import io.renren.modules.admin.entity.vo.DevHttpJsonVo;
import io.renren.modules.admin.entity.vo.SendTaskVo;
import io.renren.modules.admin.entity.vo.TaskReqVo;
import io.renren.modules.admin.service.WarmContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.admin.entity.WarmUpEntity;
import io.renren.modules.admin.service.WarmUpService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.client.RestTemplate;


/**
 * 
 *
 * @author fangzq
 * @email canglx1996@163.com
 * @date 2020-12-09 16:09:57
 */
@RestController
@RequestMapping("admin/warmup")
public class WarmUpController {
    @Autowired
    private WarmUpService warmUpService;
    @Autowired
    private WarmContentService warmContentService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private PhoneController phoneController;

    @GetMapping("api/getContext")
    public R getContext(String desc,Long userId) {

        WarmContentEntity warmContentEntity = this.warmContentService.queryByDesc(desc,"1001",userId);
        if (warmContentEntity == null) {
            return R.error("没有对应评论");
        }
        String content = warmContentEntity.getContent();
        String[] split = content.split("\\|");
        String jsonString = JSON.toJSONString(split);
        return R.ok().put("context", jsonString);
    }

    /**
     * 用于发送多个任务
     */
    @PostMapping("api/taskLists")
    public R list2(@RequestBody WarmUpEntity warmUpEntity) {
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登陆信息出错，请重新登陆");
        }
        String phoneIds = warmUpEntity.getPhoneIds();
        String replace = phoneIds.trim().replace("|", ",");

        TaskReqVo taskReqVo = new TaskReqVo();
//        taskReqVo.setUrl(warmUpEntity.getLiveAddr());
        taskReqVo.setUrl(warmUpEntity.getLiveAddr().replace("#在抖音，记录美好生活#","").replace("正在直播，来和我一起支持TA吧","")
                .replace("复制下方链接，打开【抖音】，直接观看直播",""));
        taskReqVo.setApiUrl("http://47.107.104.4:8080/renren-fast/admin/warmup/api/getContext?desc="+warmUpEntity.getCommentType()+"&userId="+userId);
        taskReqVo.setCommentType(warmUpEntity.getCommentType());
        taskReqVo.setCommentDelayStart(warmUpEntity.getCommentDelayStart());
        taskReqVo.setCommentDelayEnd(warmUpEntity.getCommentDelayEnd());
        taskReqVo.setCommentSendStart(warmUpEntity.getCommentSendStart());
        taskReqVo.setCommentSendEnd(warmUpEntity.getCommentSendEnd());
        taskReqVo.setAtRate(100);
        taskReqVo.setTaskName(warmUpEntity.getWordName());

        SendTaskVo map1 = new SendTaskVo(WarmUpEntity.OPTTYPE,taskReqVo);

        String jsonString = JSON.toJSONString(map1);

        String url = "http://dou.shciyun.com/open/common/send/tasks";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

        // 封装数据
        map.add("data", jsonString);
//            map.add("deviceId", warmUpEntity.getPhoneId().toString());
//            map.add("deviceId",freePhoneNumList.get(i));
        map.add("deviceIds",replace);
        map.add("type", "1");
//        map.add("taskName", warmUpEntity.getWordName());

        map.add("userId", String.valueOf(userId));

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );

        // 发送任务之后，保存任务到数据库
//            warmUpEntity.setPhoneId(Long.parseLong(freePhoneNumList.get(i)));
        warmUpEntity.setUserId(userId);

        warmUpEntity.setLiveAddr(taskReqVo.getUrl());
        warmUpEntity.setPhoneIds(replace);
        warmUpEntity.setCreateTime(new Date());
        warmUpService.save(warmUpEntity);
        if (response.getBody().getCode() == 200) {
            return R.ok();
        }else {
            return R.error(response.getBody().getMsg());
        }

    }

//    public static void main(String[] args) {
//        Integer[] idsInts = new Integer[5];
//        idsInts[0]=1;
//        idsInts[1]=2;
//        idsInts[2]=3;
//        idsInts[3]=4;
//        idsInts[4]=5;
//        String s1="";
//        StringBuffer sb=new StringBuffer(s1);
//        for (Integer idsInt : idsInts) {
//            sb.append(idsInt+",");
//        }
//        String s = sb.toString();
//        System.out.println("s = " + s);
//    }
    /**
     * 用于单个发送任务
     */
    @PostMapping("api/taskList")
    public R list(@RequestBody WarmUpEntity warmUpEntity){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登陆信息出错，请重新登陆");
        }

        TaskReqVo taskReqVo = new TaskReqVo();
        taskReqVo.setUrl(warmUpEntity.getLiveAddr());
        taskReqVo.setApiUrl("http://47.107.104.4:8080/renren-fast/admin/warmup/api/getContext?desc="+warmUpEntity.getCommentType()+"&userId="+userId);
        taskReqVo.setCommentType(warmUpEntity.getCommentType());
        taskReqVo.setCommentDelayStart(warmUpEntity.getCommentDelayStart());
        taskReqVo.setCommentDelayEnd(warmUpEntity.getCommentDelayEnd());
        taskReqVo.setCommentSendStart(warmUpEntity.getCommentSendStart());
        taskReqVo.setCommentSendEnd(warmUpEntity.getCommentSendEnd());
        taskReqVo.setAtRate(100);

        SendTaskVo map1 = new SendTaskVo(WarmUpEntity.OPTTYPE,taskReqVo);

        String jsonString = JSON.toJSONString(map1);

        String url = "http://dou.shciyun.com/open/common/send/task";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

        // 封装数据
        map.add("data", jsonString);
//            map.add("deviceId", warmUpEntity.getPhoneId().toString());
//            map.add("deviceId",freePhoneNumList.get(i));
        map.add("deviceId",warmUpEntity.getPhoneIds());
        map.add("type", "1");

        map.add("userId", String.valueOf(userId));

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );

        // 发送任务之后，保存任务到数据库
//            warmUpEntity.setPhoneId(Long.parseLong(freePhoneNumList.get(i)));
        warmUpEntity.setUserId(userId);
        warmUpEntity.setCreateTime(new Date());
        warmUpService.save(warmUpEntity);

        return R.ok();
    }

    /**
     * 查询所有暖场内容的评论描述
     */
    @RequestMapping("/commentType/list")
    public R queryDesc(){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        List<String> descs = this.warmContentService.queryDesc(userId);
        return R.ok().put("list", descs);
    }




    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        PageUtils page = warmUpService.queryPage(params,userId);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		WarmUpEntity warmUp = warmUpService.getById(id);
//        List<String> desc = queryDesc();

        return R.ok().put("warmUp", warmUp);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody WarmUpEntity warmUp){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        warmUp.setUserId(userId);
        warmUp.setCreateTime(new Date());
		warmUpService.save(warmUp);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody WarmUpEntity warmUp){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        warmUp.setUserId(userId);
		warmUpService.updateById(warmUp);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		warmUpService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
